<?php
namespace app\admin\controller;

use app\admin\model\Article;
use app\admin\model\Catalog;
use think\Request;

class Notebook extends Common
{
    private $catalog;
    private $article;

    public function __construct()
    {
        parent::__construct();
        $this->catalog = new Catalog();
        $this->article = new Article();
    }

    public function index()
    {
       if (Request::instance()->isPost()) {
            $post = input('post.');
            $where = [
                'cover_id' => $post['cover_id'],
                'parent_id' => 0
            ];
            $catelog_info = $this->catalog->where($where)->select();
            $article_info = $this->article->where($where)->field('id,article_title,parent_id,cover_id')->select();
            $this->assign('cover_name', $post['cover_name']);
            $this->assign('cover_id', $post['cover_id']);
            $this->assign('shelf_id', $post['shelf_id']);
            $this->assign('catelog_info', $catelog_info);
            $this->assign('article_info', $article_info);
            return $this->fetch();
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function getCatalog()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            if ($post['parent_id'] == '') {
                return $result = [
                    'code' => E_ITEM_NOT_EXIST,
                    'msg' => '未找到对应的数据库条目',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'catelog_info' => '',
                    'data' => $post,
                ];
            }
            $where = [
                'cover_id' => $post['cover_id'],
                'parent_id' => $post['parent_id']
            ];
            try {
                $catelog_info = $this->catalog->where($where)->select();
                $result = [
                    'code' => E_OK,
                    'time' => $_SERVER['REQUEST_TIME'],
                    'catelog_info' => $catelog_info,
                    'data' => $post
                ];
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ITEM_NOT_EXIST,
                    'msg' => '未找到对应的数据库条目',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $post,
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function updateCatalogName()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $result = $this->catalog->isUpdate(true)->save($post);
                if ($result == 1) {
                    $result = [
                        'code' => E_OK,
                        'time' => $_SERVER['REQUEST_TIME'],
                        'msg' => '更新成功...',
                        'data' => $post,
                    ];
                } else {
                    throw new \Exception("no data to update");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ITEM_NOT_EXIST,
                    'msg' => '更新失败...',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $post,
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }

    }

    public function addCatalog()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $res = $this->catalog->save($post);
                $post = $this->catalog->getData();
                if ($res == 1) {
                    $result = [
                        'code' => E_OK,
                        'msg' => '添加成功...',
                        'time' => $_SERVER['REQUEST_TIME'],
                        'data' => $post,
                    ];
                } else {
                    throw new \Exception("no data to add");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ITEM_NOT_EXIST,
                    'msg' => '添加失败...',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $post,
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function delCatalog()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $res[] = $post['id'];
                $ids = [0];
                do{
                    $ids = array_merge($ids,$res);
                    $res = $this->catalog->field('id')->where('parent_id','in', $res)->select()->toArray();
                    $res = array_column($res, 'id');
                } while (count($res)>0);
                $this->catalog->where('id','in',$ids)->delete();
                $this->article->where('parent_id','in',$ids)->where('cover_id','in',$post['coverid'])->delete();
                $result = [
                    'code' => E_OK,
                    'msg' => '删除成功...',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $post
                ];
            } catch (\Exception $e) {
                $result = [
                    'code' => E_DELETE_ITEM_FAILED,
                    'msg' => '删除失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function editUpload()
    {
        if (request()->isPost()) {
            $post = input('get.');
            $file = request()->file()['editormd-image-file'];
            $uploadpath = config('coverimage.absolutepath')
                . DS . 'shelf_id_' . $post['shelf_id']
                . DS . 'cover_id_' . $post['cover_id']
                . DS . date("Y-m-d", intval(time()));
            $savepath = config('coverimage.relativepath')
                . DS . 'shelf_id_' . $post['shelf_id']
                . DS . 'cover_id_' . $post['cover_id']
                . DS . date("Y-m-d", intval(time()));
            $info_origin = $file->validate(['size' => config('coverimage.size'), 'ext' => config('coverimage.ext')])
                ->move($uploadpath, $post['guid']);
            if ($info_origin) {
                $result = json_encode([
                    "success" => E_OK,
                    "msg" => "上传成功...",
                    "url"     => $savepath . DS . $info_origin->getSaveName()
                ]);
            } else {
                $result = json_encode([
                    "success" => E_UPLOAD_FAILED,
                    "msg" => "上传失败...",
                    "url" => ""
                ]);
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function imageDelete(){
        if (request()->isPost()) {
            $post = input('post.');
            $path = ROOT_PATH . 'public' . $post['imagePath'];
            if(unlink($path)){
                $result = [
                    "code" => E_OK,
                    "msg" => "图片卸载成功..."
                ];
            } else{
                $result = [
                    "code" => E_UNLOAD_FAILED,
                    "msg" => "图片卸载失败..."
                ];
            }
        } else {
            $this->redirect('admin/library/index');
        }
        return $result;
    }

    public function saveArticle(){
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                if(array_key_exists('id', $post)){
                    $res = $this->article->save($post,['id'=>$post['id']]);
                }else{
                    $res = $this->article->save($post);
                }
                $data = $this->article->getData();
                if ($res == 1) {
                    $result = [
                        'code' => E_OK,
                        'time' => $_SERVER['REQUEST_TIME'],
                        'data' => $data,
                    ];
                } else {
                    throw new \Exception("no data to update");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ITEM_NOT_EXIST,
                    'msg' => '添加失败...',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $data,
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function getArticle()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $data = $this->article->where($post)->find();
                $result = [
                    'code' => E_OK,
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $data,
                ];
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ITEM_NOT_EXIST,
                    'msg' => '获取数据失败...',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => '',
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function getArticleList()
    {
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $data = $this->article->where($post)->field('id,article_title,parent_id,cover_id')->select();
                $result = [
                    'code' => E_OK,
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => $data
                ];
            } catch (\Exception $e) {
                $result = [
                    'code' => E_ITEM_NOT_EXIST,
                    'msg' => '获取数据失败...',
                    'time' => $_SERVER['REQUEST_TIME'],
                    'data' => [],
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }

    public function delArticle(){
        if (Request::instance()->isPost()) {
            $post = input('post.');
            try {
                $rows = $this->article->where('id', $post['id'])
                    ->delete();
                if ($rows >= 1) {
                    $result = [
                        'code' => E_OK,
                        'msg' => '删除成功...',
                        'time' => $_SERVER['REQUEST_TIME'],
                        'data' => $post
                    ];
                } else {
                    throw new \Exception("no data to delete");
                }
            } catch (\Exception $e) {
                $result = [
                    'code' => E_DELETE_ITEM_FAILED,
                    'msg' => '删除失败...',
                    'time' => $_SERVER['REQUEST_TIME']
                ];
            }
            return $result;
        } else {
            $this->redirect('admin/library/index');
        }
    }
}
